package user.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import cn.zzuli.citypicker.bean.CityInfo;
import cn.zzuli.citypicker.widget.CityPickerBottomDialog;
import cn.zzuli.citypicker.utils.CityListLoader;

import com.example.xfengshopping.R;

public class CityPickerActivity extends AppCompatActivity {
    private CityPickerBottomDialog dialog;
    private EditText editTextText; // 对应布局中的EditText

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_city_picker); // 加载当前布局

        // 初始化窗口边距适配
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化城市选择器
        initCityPicker();
        // 获取布局中的EditText
        editTextText = findViewById(R.id.editTextText);
        // 设置点击事件触发城市选择弹窗
        editTextText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                dialog.show(); // 显示城市选择弹窗
                return true; // 消耗触摸事件，避免EditText获取焦点
            }
        });
    }

    private void initCityPicker() {
        // 初始化城市数据加载器
        CityListLoader.getInstance().init(this);
        // 创建底部弹窗
        dialog = new CityPickerBottomDialog(this);
        dialog.setTitle("选择地址"); // 设置弹窗标题
        dialog.setDimAmount(0.5f); // 设置背景透明度（0-1）

        // 设置选择完成回调
        dialog.setOnSubmitClickListener(new CityPickerBottomDialog.OnSubmitClickListener() {
            @Override
            public void onSubmitClick(CityInfo province, CityInfo.CityListBeanX city, CityInfo.CityListBeanX.CityListBean district) {
                // 拼接省市区地址
                String address = String.format("%s%s%s", province.name, city.name, district.name);
                // 设置地址到EditText
                editTextText.setText(address);
                // 关闭弹窗
                dialog.dismiss();
            }
        });
    }

    // 可选：重写返回键逻辑（如需禁止物理返回键可注释）
    @Override
    public void onBackPressed() {
        if (dialog.isShowing()) { // 如果弹窗正在显示，优先关闭弹窗
            dialog.dismiss();
        } else {
            super.onBackPressed(); // 否则执行默认返回逻辑
        }
    }
}